<template>
  <div class="hello">
    <svg class="map mapSvg" width="100%" height="100%" ref="">
      <defs>
        <filter id="glow">
          <feGaussianBlur class="blur" stdDeviation="25.5" result="coloredBlur" filterUnits="userSpaceOnUse"></feGaussianBlur>
          <feMerge>
            <feMergeNode in="coloredBlur"></feMergeNode>
            <feMergeNode in="SourceGraphic"></feMergeNode>
          </feMerge>
        </filter>

        <filter id="blue-glow" x="-5000%" y="-5000%" width="10000%" height="10000%">
          <feFlood result="flood" flood-color="#47a6ff" flood-opacity="1"></feFlood>
          <feComposite in="flood" result="mask" in2="SourceGraphic" operator="in"></feComposite>
          <feMorphology in="mask" result="dilated" operator="dilate" radius="2.5"></feMorphology>
          <feGaussianBlur in="dilated" result="blurred" stdDeviation="10"></feGaussianBlur>
          <feMerge>
            <feMergeNode in="blurred"></feMergeNode>
            <feMergeNode in="SourceGraphic"></feMergeNode>
          </feMerge>
        </filter>

        <filter id="glow_line">
          <feGaussianBlur class="blur" stdDeviation="10" result="coloredBlur" filterUnits="userSpaceOnUse"></feGaussianBlur>
          <feMerge>
            <feMergeNode in="coloredBlur"></feMergeNode>
            <feMergeNode in="SourceGraphic"></feMergeNode>
          </feMerge>
        </filter>

        <filter id="glow_line2">
          <feGaussianBlur class="blur" stdDeviation="1.5" result="coloredBlur" filterUnits="userSpaceOnUse"></feGaussianBlur>
          <feMerge>
            <feMergeNode in="coloredBlur"></feMergeNode>
            <feMergeNode in="SourceGraphic"></feMergeNode>
          </feMerge>
        </filter>
      </defs>
    </svg>
  </div>
</template>

<script>
  import * as d3 from 'd3'
  import * as topojson from 'topojson'
  import toporoot from './chinaMap'
  import _ from 'lodash'
  import  $ from 'jquery'

export default {
  name: 'hello',
  data () {
    return {
      locations:[{
        provience:"新疆",
        hospitals:[
          {hospitalName:"美年---XX分院",
            coordinate:[86,44],
            lastTicket:{
              status:"待接修",
              deviceName:"核磁共振设备",
              department:"XXX科室"
            }},

          {hospitalName:"美年---OO分院",
            coordinate:[80,40],
            lastTicket:{
              status:"待接修",
              deviceName:"核磁共振设备",
              department:"XXX科室"
            }}

        ]
      },
        {
          provience:"四川",
          hospitals:[
            {hospitalName:"美年---YY分院",
              coordinate:[104,30],
              lastTicket:{
                status:"待接修",
                deviceName:"核磁共振设备",
                department:"XXX科室"
              }}
          ]
        }]
    }
  },
  methods:{
    initChinaMap(){
      let width = 580
      let height = 580
      d3.select('svg.map').selectAll('.gContainer').remove()

      let svg = d3.select('svg.map').attr('transform', 'translate(' + 0 + ',' + 0 + ')').append('g').attr('transform', 'translate(' + 30 + ',' + 60 + ')').attr('class', 'gContainer')

      let projection = this.projection = d3.geoMercator()
        .center([107, 31])
        .scale(500)
        .translate([width / 2, height / 2])

      let path = d3.geoPath()
        .projection(projection)


      // 将TopoJSON对象转换成GeoJSON，保存在georoot中
      var georoot = topojson.feature(toporoot, toporoot.objects.china)
      var mergePolygon = topojson.merge(toporoot, toporoot.objects.china.geometries.filter(function (d) {
        return true
      }))
      var chinaBg = svg.append('g').attr('class', 'china_bg_map')
      var chinaProvience = svg.append('g').attr('class', 'china_provience')


      // 添加中国各种的路径元素
      // 省份
      chinaProvience.selectAll('path')
        .data(georoot.features)
        .enter()
        .append('path')

        .attr('d', path)
        .on("click", function(args){
          d3.selectAll("#highLight").attr('id','')
          d3.selectAll("#highLight").attr('data_name',args.properties.name)
          d3.select(this).attr('id','highLight')
          console.log("当前点击的是:",args.properties.name)

        },true)
        .attr('stroke', '#82e3ff')
        .style('filter', 'url(#glow_line2)')
        .style('stroke-width', .5)
        .style('stroke-opacity', 0.5)
        .attr('class', 'province11')
        .attr('name', function(args){
          return args.properties.name
        })
        .style('fill', '#f00')
        .style('fill-opacity', '0')


      // 背景
      chinaBg.append('path')
        .datum(mergePolygon)
        .attr('class', 'border')
        //          .style('fill', '#47a6ff')  // 用蓝色标注
        //        .style('fill-opacity', '0.1')
        .style('fill', '#47a6ff')  // 用蓝色标注
        .style('fill-opacity', '0.1')
//        .style('filter', 'url(#blue-glow)')
        .attr('stroke', '#82e3ff')
        .attr('stroke-opacity', '1')
        .attr('stroke-width', 2)
        .attr('d', path)
    },
    loopHosLocation(){

      //show solo coordinate
      this.locations.forEach((provience)=>{
          // solo provience
          console.log(provience, this)
          provience.hospitals.forEach((hos)=>{
            //solo hospital
            this.showCoord(provience.provience, hos.coordinate)

          })

      })

    },
    showCoord(provienceName,coord){
      //get GPS location data
      let posHospital = this.projection(coord)

      let svg = d3.select('svg.map')
      let allDots = d3.select('.all_dots')
      if(allDots.empty()){
        //if no all dots
        let svg = d3.select('g.gContainer')
        allDots = svg.append('g').attr('class', 'all_dots')
                  .style('filter', 'url(#glow_line)')
      }

      let curG = allDots.append("g").attr('name',provienceName).style("fill-opacity",0.3)
      //append
      curG.append('circle')
                  .attr('class', 'point')
                  .attr('cx', posHospital[0])
                  .attr('cy', posHospital[1])
                  .attr('r', 14)
                  .attr('fill', '#a3a977')

      curG.append('circle')
                  .attr('class', 'point')
                  .attr('cx', posHospital[0])
                  .attr('cy', posHospital[1])
                  .attr('r', 8)
                  .attr('fill', '#ffed86')


    },
    async showProvienceRandom(){
      let areasLength = this.locations.length - 1;
      let randomIndex = _.random(0,areasLength);
      d3.selectAll("path.province11").attr("id",'')
      let provienceName = this.locations[randomIndex].provience;
      d3.select(`.china_provience path[name=${provienceName}]`).attr("id","highLight")

      d3.selectAll(`.all_dots g`).attr("id","")
      d3.selectAll(`.all_dots g[name=${provienceName}]`).attr("id","opacity100")
      console.log('begin------','即将展示的是',provienceName)
      await this.showProvience(this.locations[randomIndex])
      console.log('----------------')
      this.showProvienceRandom()

    },
    showProvience(soloProvience){
      return new Promise((resolve,reject)=>{
        let allHosLength = soloProvience.hospitals.length;
        let count = 0;
        this.showFocuesDot(soloProvience,count)
        ++count
        let t= setInterval(()=>{
          if(count === allHosLength){
            console.log("当前区域的循环结束")
            clearInterval(t);
            resolve()
            return
          }
          this.showFocuesDot(soloProvience,count)
//          this.showLine(provience.hospitals[count])
          ++count;
        },3000)
      })
    },
    showFocuesDot(soloProvience,index){
      let provienceName = soloProvience.provience;
//      let id = d3.selectAll(`.all_dots g[name=${provienceName}]`)[index].attr("id")
      let selectedHos = $(`.all_dots g[name=${provienceName}]`).eq(index)
      $(".all_dots g").removeClass('focus');
      selectedHos.addClass("focus")

    }


  },
  mounted(){
    //initial map bg
    this.initChinaMap();
    // render all hospital
    this.loopHosLocation();
    //random show provience
    this.showProvienceRandom()
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style  lang="scss">
  @import "../assets/css/common.scss";
  #highLight{
    fill: #ffed86 !important;
    fill-opacity: 0.1 !important;
    stroke-width: 2 !important;
    stroke: #ffed86 !important;
    stroke-opacity:1 !important;
  }

  #opacity100{
    fill-opacity: 1 !important;
    &.focus{
       circle:nth-child(1) {
         fill:#a38e7c !important;
       }
      circle:nth-child(2) {
         fill:#ffa08a !important;
       }
    }
  }
</style>
